package com.erbao.interview;

import java.util.ArrayList;
import java.util.List;

/**
 * 实现一个容器，提供方法：add、size
 * 写两个线程，线程1添加10个元素到容器，线程2监控元素的个数，当个数到5个时，线程2给出提示并结束
 *
 * 监控属于被动，通知属于主动。监控晚人一步，容易出问题(例如超过5个到了6个才监控到)。
 * @author CaoBaoYin
 * @since 2022/2/27 17:17
 */
public class ThreadNotice {


    public static void main(String[] args) {
        new ThreadNotice().waitNotify();
    }

    void waitNotify() {
        final Capacity<Integer> capacity = new Capacity<>();
        final Object o = new Object();

        Thread t1 = new Thread(() -> {
            System.out.println("t1 开始");
            synchronized (o) {
                for (int i = 0; i < 10; i++) {
                    System.out.println(i);
                    capacity.add(i);
                    if (capacity.size() == 5) {
                        o.notify();
                        try {
                            o.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
            System.out.println("t1 end");
        });

        Thread t2 = new Thread(() -> {
            System.out.println("t2 进入线程");
            synchronized (o) {
                if (capacity.size() != 5) {
                    try {
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("t2 获取到通知,容器大小："+capacity.size());
                o.notify();
            }

            System.out.println("t2 结束");
        });

        t1.start();
        t2.start();
    }
}

class Capacity <T> {
    private List<T> list = new ArrayList<>(10);

    public void add (T e) {
        list.add(e);
    }

    public int size () {
        return list.size();
    }
}
